import { defineStore } from "pinia";
import { addCart, changeItemNum } from "@/api";
import { showToast } from "vant";
const useCartStore = defineStore('cart', {
  state: () => ({
    // 购物车中的商品
    items: [],
    number: 0, // 总件数
    price: 0 // 总价格
  }),
  actions: {
    initCart({items, number, price}: any){
      this.items = items;
      this.number = number;
      this.price = price;
    },
    // 修改商品购买数量
    changeItemNum(key: string, number: number){
      changeItemNum({
        key,
        number
      }).then(res => {
        if (res.data.code ===0) {
          this.initCart(res.data.data)
          showToast('修改数量成功')

        }
        
      })
    },
    // 加入购物车
    addCart(goodsId:number, number: number){
      addCart({
        goodsId,
        number
      }).then(res => {
        if (res.data.code ===0) {
          this.initCart(res.data.data)
          showToast('加入购物车成功')

        }
        
      })
    }
  },
  persist: true
}) 

export default useCartStore